package com.woniuxy.rabbitmq79.send.confirm;

import com.rabbitmq.client.*;

import java.io.IOException;

/**
 * @Author zhangyong
 * @Date 2021/8/12 0012上午 10:00
 */
public class Productor {
    //交换机名字
    private static final String EXCHANGE_NAME = "confirm_exchange";
    //路由
    private static final String ROUTE_KEY = "send";
    
    public static void main(String[] args)throws Exception {
        //1.创建连接工厂：创建连接
        ConnectionFactory factory = new ConnectionFactory();

        //2.设置连接参数
        factory.setHost("localhost");   //mq的ip
        factory.setUsername("guest");   //账号
        factory.setPassword("guest");   //密码
        factory.setVirtualHost("/");    //设置虚拟主机 不设置默认/

        //3.创建连接
        Connection connection = factory.newConnection();     //IO异常

        //4.创建通道
        Channel channel = connection.createChannel();

        //手动的指定开启confirm确认  confirm模式
        channel.confirmSelect();
        
        //获取交换机
        channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.DIRECT);

        //添加一个监听器：监听mq返回的结果
        channel.addConfirmListener(new ConfirmListener() {
            //成功时调用的方法
            @Override
            public void handleAck(long tag, boolean multiple) throws IOException {
                //tag   消息id    multiple   是否批量确认
                System.out.println("success"+tag);
            }

            //失败时调用的方法
            @Override
            public void handleNack(long tag, boolean multiple) throws IOException {
                //tag   消息id    multiple   是否批量确认
                System.out.println("fail"+tag);
            }
        });
        channel.basicPublish(EXCHANGE_NAME,ROUTE_KEY,null,"hello".getBytes());

        //别关channel /connect 因为发送出去直接关闭没知识生产者程序结束，无法接受到mq返回的消息

    }
}
